package com.briup.estore.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.briup.estore.bean.Customer;
import com.briup.estore.result.ResCode;
import com.briup.estore.result.Result;
import com.briup.estore.service.ICustomerService;

@Controller
public class do_login_before {

	@Autowired
	private ICustomerService customerService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(Customer customer, HttpServletRequest request, HttpSession session, ModelAndView model)
			throws Exception {
		Result result = customerService.loginCustomer(customer);
		if (result.getCode() == ResCode.CODE_SUCCESS) {
			Customer customer2 = (Customer) result.getResult();
			customer2.setPwd(null);
			session.setAttribute("customer", customer2);
			String path = (String) session.getAttribute("path");
			System.out.println("path>>>>>>>>" + path);
			if (path != null) {
				model.setViewName("redirect:" + path);
				return model;
			}
			model.setViewName("redirect:/index");
			return model;
		}
		model.addObject("msg", result.getMsg());
		model.setViewName("/login");
		return model;
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView register(Customer customer, HttpServletRequest request, HttpSession session, ModelAndView model)
			throws Exception {
		Result result = customerService.registerCustomer(customer);
		model.addObject("msg", result.getMsg());

		if (result.getCode() == ResCode.CODE_SUCCESS) {
			model.setViewName("/login");
		} else {
			model.setViewName("/register");
		}
		return model;
	}

	@RequestMapping("/exit")
	public String exit(HttpSession session) {
		session.removeAttribute("customer");
		return "redirect:/index";
	}
}
